package com.lagace.spark.twitter;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;

import org.jivesoftware.spark.PluginManager;
import org.jivesoftware.spark.preference.Preference;

import com.lagace.spark.twitter.local.LocalTwitterPreferences;
import com.lagace.spark.twitter.local.TwitterSettingsManager;

public class TwitterPreferences implements Preference{

	private TwitterPreferenceUI ui;
	private LocalTwitterPreferences preferences;
	
	public TwitterPreferences() {
		preferences = TwitterSettingsManager.getLocalTwitterPreferences();
		ui = new TwitterPreferenceUI();
	}
	
	public TwitterPreferenceUI getUI(){
		return ui;
	}
	
	public void commit() {
		LocalTwitterPreferences pref = TwitterSettingsManager.getLocalTwitterPreferences();

    	pref.setUsername(ui.getUsername());
    	pref.setPassword(ui.getPassword());
    	pref.setRefreshTime(ui.getRefresh());
        
        TwitterSettingsManager.saveSettings();
        
        reloadPlugin();
	}

	private void reloadPlugin() {
		PluginManager pm = PluginManager.getInstance();
		TwitterPlugin p = (TwitterPlugin) pm.getPlugin(com.lagace.spark.twitter.TwitterPlugin.class);
        p.reloadPlugin();
	}

	public Object getData() {
		return null;
	}

	public String getErrorMessage() {
		return null;
	}

	public JComponent getGUI() {
		return ui;
	}

	public Icon getIcon() {
		try {
			return new ImageIcon(ImageIO.read(getClass().getResource("/twitter_icon.png")));
		} catch (IOException e ) { /*this should never happen*/	}
		return null;
	}

	public String getListName() {
		return "Twitter";
	}

	public String getNamespace() {
		return "TWITTER";
	}

	public String getTitle() {
		return "Twitter Preferences";
	}

	public String getTooltip() {
		return "Example tooltip in preference dialog";
	}

	public boolean isDataValid() {
		return true;
	}

	public void load() {
		ui.setUsername(preferences.getUsername());
		ui.setPassword(preferences.getPassword());
		ui.setRefresh(preferences.getRefreshTime());
	}

	public void shutdown() {
		commit();
	}
}